package com.roc.web.action.setting;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseAction;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.ExcelBean;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.setting.ISettflagService;
import com.roc.service.setting.ISettingExcelService;
import com.roc.util.Constance;
import com.roc.util.ExcelUtil;
import com.roc.util.Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.estrn.EstrnHisInfoSearchCondition;
import com.roc.web.action.setting.HRTSettingSearchCondition;

@Component
@Scope("prototype")
@Namespace("/settingCreateExcel")
@SuppressWarnings("all")
public class SettingCreateExcelAction extends BaseAction {
	static Logger logger = Logger.getLogger(SettingCreateExcelAction.class);
	@Autowired
	ISettingExcelService excelService;
	@Autowired
	ISettflagService settflagService;
	private HRTSettingSearchCondition searchCondition;

	private String msg;
	private String modelFlag;
	private String minDate;
	private String maxDate;
	private String excelFlag;

	private InputStream excelFile;

	// private String excelName;
	// 结算导出excel
	@Action(value = "create", results = {
			@Result(name = "success", location = "/pages/setting/settingCreate.jsp"),
			@Result(name = "error", location = "/pages/setting/settingCreate.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp") })
	public String settingExcelqQuery() {
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		String mid = null;

		try {
			if (minDate == null || minDate.trim().length() == 0) {
				addActionError("请选择结算起始日期！");
				return ERROR;
			}
			if (maxDate == null || maxDate.trim().length() == 0) {
				addActionError("请选择结算终止日期！");
				return ERROR;
			}

			boolean isTrue = Constance.theDateIsTrue(minDate, maxDate);
			if (!isTrue) {
				addActionError("您选择的结算日期必须在一个月之内！");
				return ERROR;
			}
			if (modelFlag == null || modelFlag.trim().length() == 0) {
				addActionError("请选择报表类型！");
				return ERROR;
			}
			if (excelFlag == null || excelFlag.trim().length() == 0) {
				addActionError("请选择结算渠道！");
				return ERROR;
			}
			minDate = minDate.replace("-", "");
			maxDate = maxDate.replace("-", "");
			// HttpServletResponse response = (HttpServletResponse)
			// ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
			// response.reset();
			// try {
			// response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			// response.setHeader("Content-disposition",
			// "attachment;filename=\""+ new
			// String(("服务项目.xls").getBytes("GBK"),"ISO-8859-1") + "\"");
			// //这里的是要导出的文件显示的名字
			// } catch (UnsupportedEncodingException e1) {
			// msg = "不支持编码异常！";
			// }
			// String filePath = "d:/templateFile/";
			// InputStream is = new FileInputStream(filePath+
			// "/服务项目.xls");//这里是文件的模板
			//			
			// 生产路径settingExcelPathSC
			// settingExcelPathtest
			String filePath = Utils.getConfigValue("settingExcelPathSC");

			String excelname = getExcelName(modelFlag, excelFlag);
			FileOutputStream os = null;
			os = new FileOutputStream(filePath + excelname);
			System.out.println(filePath + excelname);
			HSSFWorkbook work = excelService.settingExcel(minDate, maxDate,
					modelFlag, excelFlag);
			work.write(os);
			os.flush();
			if (os != null) {
				os.close();
			}
			ExcelBean exb = new ExcelBean();
			exb = getexcelBean(minDate, maxDate, excelname, modelFlag,
					excelFlag);
			int i = 0;
			i = settflagService.updatesetting(minDate, maxDate, modelFlag,
					excelFlag, exb);
			if (i != 0) {
				addActionMessage("生成结算报表成功");
			} else {
				addActionMessage("生成结算报表失败");
			}
		} catch (Exception e) {
			logger.info("######导出Excel失败######");
			addActionError("生成结算报表失败");
			System.out.print(e);
			return ERROR;
		}

		return SUCCESS;
	}

	// 结算初始页面
	@Action(value = "settingCreateinit", results = {
			@Result(name = "success", location = "/pages/setting/settingCreate.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String settingCreateinit() throws Exception {
		// List settingflagList=new ArrayList();
		// settingflagList=settflagService.querySettingFlagList();
		// getRequest().setAttribute("settingflagList", settingflagList);
		return SUCCESS;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public ExcelBean getexcelBean(String minDate, String maxDate,
			String excelName, String modelFlag, String excelFlag) {
		ExcelBean exb = new ExcelBean();
		exb.setStartDate(minDate);
		exb.setEndDate(maxDate);
		exb.setExcelName(excelName);
		Date cDate = new Date();
		String cStr = DateFormatUtils.format(cDate, "yyyyMMdd");
		exb.setCreateDate(cStr);
		exb.setModelFlag(modelFlag);
		exb.setExcelFlag(excelFlag);
		return exb;
	}

	public String getExcelName(String modelFlag, String excelFlag) {
		Date cDate = new Date();

		String cStr = DateFormatUtils.format(cDate, "yyyy-MM-dd");
		String excelName = "";
		try {
			excelName = settflagService.selectExcelName(modelFlag, excelFlag);

			if (!"".equals(excelName)) {
				String[] ss = excelName.split("-");
				if(ss.length==4){
					excelName=ss[0] + "-" + ss[1]+ "-" + ss[2] + "-" + ss[3].substring(0, ss[3].indexOf("."))+ "-1.xls";
				}else if(ss.length==5){
					String oder = ss[4].substring(0, ss[4].indexOf("."));
					int oder1 = Integer.valueOf(oder);
					excelName = ss[0] + "-" + ss[1] + "-" + ss[2] + "-" + ss[3]
							+ "-" + String.valueOf(oder1 + 1)+ ".xls";
				}else{
					String oder = ss[4];
					int oder1 = Integer.valueOf(oder);
					excelName = ss[0] + "-" + ss[1] + "-" + ss[2] + "-" + ss[3]
							+ "-" + String.valueOf(oder1 + 1) + "-" + ss[5];	
				}
				
			} else {
				if("q".equals(modelFlag)){
					excelName =  cStr + "-和融通.xls";
				}else if ("g".equals(modelFlag)) {
					excelName = "b2e0009-" + cStr + "-1-银嘉金融公对公.xls";
				} else if ("c".equals(modelFlag)) {
					excelName = "b2e0351-" + cStr + "-1-银嘉金融新跨行转账.xls";
				} else if ("k".equals(modelFlag)) {
					excelName = "b2e0078-" + cStr + "-1-银嘉金融快捷代发.xls";
				} else if ("d".equals(modelFlag)) {
					excelName = "b2e0078-" + cStr + "-1-银嘉金融姓名带点.xls";
				}else if ("w".equals(modelFlag)) {
					excelName = "b2e0000-" + cStr + "-1-未结算.xls";
				}
			}
			// excelName = new String(excelName.getBytes("utf-8"),"ISO8859-1");
		} catch (ServiceException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return excelName;

	}

	public HRTSettingSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(HRTSettingSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getModelFlag() {
		return modelFlag;
	}

	public void setModelFlag(String modelFlag) {
		this.modelFlag = modelFlag;
	}

	public String getMinDate() {
		return minDate;
	}

	public void setMinDate(String minDate) {
		this.minDate = minDate;
	}

	public String getMaxDate() {
		return maxDate;
	}

	public void setMaxDate(String maxDate) {
		this.maxDate = maxDate;
	}

	public String getExcelFlag() {
		return excelFlag;
	}

	public void setExcelFlag(String excelFlag) {
		this.excelFlag = excelFlag;
	}

}
